<?php

/*
=====================================================
 I-Soft Bizness - внедрение и модификация I-Soft
-----------------------------------------------------
 http://vkaragande.info/
-----------------------------------------------------
 Created by D.Madi
=====================================================
 Файл: edcat.php
-----------------------------------------------------
 Назначение: Редактирование категорий
=====================================================
*/

session_start();

require_once './defaults.php';

check_login_cp('2_3','edcat.php');

if (isset($_POST['sort_cat']))
{
	$_SESSION['sort_cat'] = (string)$_POST['sort_cat'];
}

if (empty($_SESSION['sort_cat']))
{
	$_SESSION['sort_cat'] = 'selector';
}

if (isset($_POST['sort_subcat']))
{
	$_SESSION['sort_subcat'] = (string)$_POST['sort_subcat'];
}

if (empty($_SESSION['sort_subcat']))
{
	$_SESSION['sort_subcat'] = 'catsubsel';
}

if (isset($_POST['sort_subsubcat']))
{
	$_SESSION['sort_subsubcat'] = (string)$_POST['sort_subsubcat'];
}

if (empty($_SESSION['sort_subsubcat']))
{
	$_SESSION['sort_subsubcat'] = 'catsubsubsel';
}

if ((empty ($_GET['edcat'])) and (empty ($_GET['edsubcat']))) {

$help_section = (string)$cat_help;

$title_cp = $def_admin_edcat.' - ';
$speedbar = ' | <a href="edcat.php">'.$def_admin_edcat.'</a>';

require_once 'template/header.php';

table_item_top ($def_admin_edcat,'tmpl.png');

?>

<form action="edcat.php" method="post">
 &nbsp;&nbsp;Сортировать<br />&nbsp;&nbsp;Категории по:
  <select name="sort_cat" onchange="this.form.submit();">
    <option value="selector" <? if ($_SESSION['sort_cat']=='selector') echo 'selected="selected"'; ?>>по id</option>
    <option value="category" <? if ($_SESSION['sort_cat']=='category') echo 'selected="selected"'; ?>>по алфавиту</option>
  </select>
&nbsp;<img src="images/info_t.gif" width="5" height="22" align="absmiddle">&nbsp;Подкатегории по:
  <select name="sort_subcat" onchange="this.form.submit();">
    <option value="catsubsel" <? if ($_SESSION['sort_subcat']=='catsubsel') echo 'selected="selected"'; ?>>по id</option>
    <option value="subcategory" <? if ($_SESSION['sort_subcat']=='subcategory') echo 'selected="selected"'; ?>>по алфавиту</option>
  </select>
&nbsp;<img src="images/info_t.gif" width="5" height="22" align="absmiddle">&nbsp;Разделы подкатегорий по:
  <select name="sort_subsubcat" onchange="this.form.submit();">
    <option value="catsubsubsel" <? if ($_SESSION['sort_subsubcat']=='catsubsubsel') echo 'selected="selected"'; ?>>по id</option>
    <option value="subsubcategory" <? if ($_SESSION['sort_subsubcat']=='subsubcategory') echo 'selected="selected"'; ?>>по алфавиту</option>
  </select>
<br /><br />
</form>
     
<?

$allowcats="YES";

$cat_disp = safehtml ($_POST[disp]);
$calias = safehtml ($_POST[calias]);
if(!$calias) $calias = rewrite ($cat_disp);

	if (($_POST["submit"] != "$def_admin_delcat") and (!empty($_POST["submit"])) and (empty($cat_disp))) { msg_text('80%',$def_admin_message_error,$def_empty); }

	else

	{
		if ($_POST["submit"] =="$def_admin_addcat")
		{
			$r=$db->query ("select MAX(selector) AS maxselector from $db_category") or die ("mySQL error!");

			$f=$db->fetcharray ($r);
			$newselector=$f["maxselector"]+1;
			mysql_free_result($r);

			$r=$db->query ("insert into $db_category (selector, category, calias) values ('$newselector', '$cat_disp', '$calias')") or die ("mySQL error!");

                        logsto("$def_admin_log_newcatadded $cat_disp");
		}

		elseif ($_POST["submit"] == "$def_admin_addsubcat")

		{
			$r=$db->query ("select MAX(catsubsel) AS maxsubsel from $db_subcategory") or die ("mySQL error!");

			$oldcat = explode("::", $_POST["chosen"]);
			$f=$db->fetcharray ($r);
			$newsubselector=$f["maxsubsel"]+1;
			mysql_free_result($r);

			if ($oldcat[0]!='') {

			$r=$db->query ("select * from $db_category where selector=$oldcat[0]") or die ("mySQL error!");
			$f=$db->fetcharray ($r);
			mysql_free_result($r);

			}

			if (

			($f[fcounter] == 0) or

			(($f[fcounter] != 0) and ($allowcats == "YES")) or

			(($f[fcounter] != 0) and ($f[sccounter] != 0) and ($f[ssccounter] == 0))

			)

			{
				if (($oldcat[0] != "") and ($oldcat[0] != "0"))

				{
					$r=$db->query ("insert into $db_subcategory (catsel, catsubsel, subcategory, calias) values ('$oldcat[0]', '$newsubselector', '$cat_disp', '$calias')") or die ("mySQL error!");

					$db->query  ( " UPDATE $db_category SET sccounter = sccounter+1 where selector = '$oldcat[0]' " ) or die ( mysql_error() );

                                        logsto("$def_admin_log_newsubcatadded $cat_disp");
				}

				else msg_text('80%',$def_admin_message_error,$def_error_addcat1);

			}

			else msg_text('80%',$def_admin_message_error,$def_error_addcat4);

		}

		elseif ($_POST["submit"] == "$def_admin_addsubsubcat")

		{
			$oldcat = explode("::", $_POST["chosen"]);

			$r=$db->query ("select * from $db_subcategory where catsel='$oldcat[0]' and catsubsel='$oldcat[1]'") or die ("mySQL error!");
			$f=$db->fetcharray ($r);
			mysql_free_result($r);

			if (

			($f[fcounter] == 0) or

			(($f[fcounter] != 0) and ($allowcats == "YES")) or

			(($f[fcounter] != 0) and ($f[ssccounter] != 0 ))

			)

			{
				if (($oldcat[1] != "") and ($oldcat[1] != "0") and ($oldcat[0] != "") and ($oldcat[0] != "0"))

				{
					$r=$db->query ("select MAX(catsubsubsel) AS maxsubsubsel from $db_subsubcategory") or die ("mySQL error!");
					$f=$db->fetcharray ($r);
					$newsubselector=$f["maxsubsubsel"]+1;

					$r=$db->query ("insert into $db_subsubcategory (catsel, catsubsel, catsubsubsel, subsubcategory) values ('$oldcat[0]', '$oldcat[1]', '$newsubselector', '$cat_disp')") or die ("mySQL error!");

					$db->query  ( " UPDATE $db_category SET ssccounter = ssccounter+1 where selector = '$oldcat[0]' " ) or die ( mysql_error() );
					$db->query  ( " UPDATE $db_subcategory SET ssccounter = ssccounter+1 where catsel = '$oldcat[0]' AND catsubsel = '$oldcat[1]'" ) or die ( mysql_error() );

                                        logsto("$def_admin_log_newsubsubcatadded $cat_disp");
				}
				else msg_text('80%',$def_admin_message_error,$def_error_addcat2);
			}
			else msg_text('80%',$def_admin_message_error,$def_error_addcat5);
		}

		elseif ($_POST["submit"] == "$def_admin_catren")

		{
			$cat = explode("::", $_POST["chosen"]);
			$cat0=$cat[0];
			$cat1=$cat[1];
			$cat2=$cat[2];

			if ($cat1 == "")

			{
				$r=$db->query ("SELECT * from $db_category where selector='$cat0'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$db->query ("UPDATE $db_category SET category='$cat_disp' where selector='$cat0'") or die ("mySQL error!");

                                logsto("$def_admin_log_catrenamed  $f[category] -> $cat_disp");
			}

			if (($cat1 != "") and ($cat2 == ""))

			{
				$r=$db->query ("SELECT * from $db_subcategory where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$db->query ("UPDATE $db_subcategory SET subcategory='$cat_disp' where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");

                                logsto("$def_admin_log_subcatrenamed  $f[subcategory] -> $cat_disp");

			}

			if (($cat1 != "") and ($cat2 != ""))

			{
				$r=$db->query ("SELECT * from $db_subsubcategory where catsel='$cat0' and catsubsel='$cat1' and catsubsubsel='$cat2'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$db->query ("UPDATE $db_subsubcategory SET subsubcategory='$cat_disp' where catsel='$cat0' and catsubsel='$cat1' and catsubsubsel='$cat2'") or die ("mySQL error!");

                                logsto("$def_admin_log_subsubcatrenamed  $f[subsubcategory] -> $cat_disp");
			}
		}

		elseif ($_POST["submit"] == "$def_admin_delcat")

		{
			$cat = explode("::", $_POST["chosen"]);
			$cat0=$cat[0];
			$cat1=$cat[1];
			$cat2=$cat[2];

			if ($cat1 == "")

			{
				$r=$db->query ("SELECT * from $db_category where selector='$cat0'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$exists=mysql_numrows($r);
				mysql_free_result($r);

				if (($f[fcounter] == 0) and ( $f[sccounter] == 0) and ($f[ssccounter] == 0) and ($exists != 0))
				{

					$r=$db->query ("SELECT * from $db_category where selector='$cat0'") or die ("mySQL error!");
					$f=$db->fetcharray ($r);

					$db->query ("delete from $db_category where selector='$cat0'") or die ("mySQL error!");

					$db->query ("delete from $db_subcategory where catsel='$cat0'") or die ("mySQL error!");

					$db->query ("delete from $db_subsubcategory where catsel='$cat0'") or die ("mySQL error!");

                                        logsto("$def_admin_log_catdeleted  $f[category]");

				}

				else msg_text('80%',$def_admin_message_error,$def_admin_edcat10);
			}

			if (($cat1 != "") and ($cat2 == ""))
			{
				$r=$db->query ("SELECT * from $db_subcategory where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$exists=mysql_numrows($r);

				mysql_free_result($r);

				if (($f[fcounter] == 0) and ($f[ssccounter] == 0) and ($exists != 0))
				{
					$r=$db->query ("SELECT * from $db_subcategory where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");
					$f=$db->fetcharray ($r);

					$db->query ("delete from $db_subcategory where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");

					$db->query ("delete from $db_subsubcategory where catsel='$cat0' and catsubsel='$cat1'") or die ("mySQL error!");

					$db->query  ( " UPDATE $db_category SET sccounter = sccounter-1 where selector = '$cat[0]' " ) or die ( mysql_error() );

                                        logsto("$def_admin_log_subcatdeleted  $f[subcategory]");
				}
				else msg_text('80%',$def_admin_message_error,$def_admin_edcat11);
			}

			if (($cat1 != "") and ($cat2 != ""))
			{
				$r=$db->query ("SELECT * from $db_subsubcategory where catsel='$cat0' and catsubsel='$cat1' and catsubsubsel='$cat2'") or die ("mySQL error!");
				$f=$db->fetcharray ($r);

				$exists=mysql_numrows($r);

				mysql_free_result($r);

				if (($f[fcounter] == 0) and ($exists != 0))
				{
					$r=$db->query ("SELECT * from $db_subsubcategory where catsel='$cat0' and catsubsel='$cat1' and catsubsubsel='$cat2'") or die ("mySQL error!");
					$f=$db->fetcharray ($r);

					$db->query ("delete from $db_subsubcategory where catsel='$cat0' and catsubsel='$cat1' and catsubsubsel='$cat2'") or die ("mySQL error!");

					$db->query  ( " UPDATE $db_category SET ssccounter = ssccounter-1 where selector = '$cat[0]' " ) or die ( mysql_error() );
					$db->query  ( " UPDATE $db_subcategory SET ssccounter = ssccounter-1 where catsel = '$cat[0]' AND catsubsel = '$cat[1]'" ) or die ( mysql_error() );

                                        logsto("$def_admin_log_subsubcatdeleted  $f[subsubcategory]");
				}
				else msg_text('80%',$def_admin_message_error,$def_admin_edcat12);
			}
		}
	}

	table_fdata_top ($def_item_form_data);

	$r=$db->query ("select * from $db_category  ORDER BY $_SESSION[sort_cat]") or die ("mySQL error!");
	$results_amount=mysql_numrows($r);

	echo '<table width="70%" border="0" cellpadding="0" cellspacing="0">';
	echo '<form method="post" action="edcat.php">';

	for ($x=0;$x<$results_amount;$x++){
		$f=$db->fetcharray ($r);

                if ($f[img]!='') $img_ok='<img src="images/img_cat.png" width="24" height="24" align="absmiddle" border="0" alt="Иконка" title="Иконка" hspace="2" vspace="2" />'; else $img_ok='';

		echo '<tr><td width="100%" align="left" valign="top"><input type="radio" name="chosen" value="'.$f[selector].'" style="border:0;" /><b style="color: #0000FF">'.$f[category].'</b> <a href="?edcat='.$f[selector].'" title="Редактировать"><img src="images/edit_cat.png" width="24" height="24" align="absmiddle" border="0" alt="Редактировать" title="Редактировать" hspace="2" vspace="2" /></a>'.$img_ok.'<span style="color: #999999; font-size:9px;">(id '.$f[selector].', subs: '.$f[sccounter].'/ subsubs: '.$f[ssccounter].'/ listings: <b>'.$f[fcounter].'</b>)</span><br /></td></tr>';
                echo "\n";

		$re=$db->query ("select * from $db_subcategory where catsel=$f[selector] ORDER BY $_SESSION[sort_subcat]") or die ("mySQL error!");
		$results_amount2=mysql_numrows($re);

		for ($x1=0;$x1<$results_amount2;$x1++){

			$fe=$db->fetcharray ($re);

			echo '<tr><td width="100%" align="left" valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="chosen" value="'.$f[selector].'::'.$fe[catsubsel].'" style="border:0;" /><b style="color: #006600">'.$fe[subcategory].'</b> <a href="?edsubcat='.$fe[catsubsel].'" title="Редактировать"><img src="images/edit_cat.png" width="24" height="24" align="absmiddle" border="0" alt="Редактировать" title="Редактировать" hspace="2" vspace="2" /></a>'.$img_ok.'<span style="color: #999999; font-size:9px;">(id '.$fe[catsubsel].', subsubs: '.$fe[ssccounter].'/ listings: <b>'.$fe[fcounter].'</b>)</span><br /></td></tr>';
                        echo "\n";

			$ree=$db->query ("select * from $db_subsubcategory where catsubsel=$fe[catsubsel] and catsel=$f[selector] ORDER BY $_SESSION[sort_subsubcat]") or die ("mySQL error!");

			$results_amount3=mysql_numrows($ree);

			for ($y1=0;$y1<$results_amount3;$y1++){

				$fee=$db->fetcharray ($ree);

				echo '<tr><td width="100%" align="left" valign="top">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="chosen" value="'.$f[selector].'::'.$fe[catsubsel].'::'.$fee[catsubsubsel].'"  style="border:0;" />'.$fee[subsubcategory].' <span style="color: #999999; font-size:9px;">(id '.$fee[catsubsubsel].', listings: <b>'.$fee[fcounter].'</b>)</span><br /></td></tr>';
                                echo "\n";
			}
		}
	}

	echo '<tr><td width="100%" align="left" valign="top">';
	echo '<br /><br />Имя(например:Вода): <input type="text" size="50" name="disp" /><br /><br />
	Альтернативное имя(например:Voda): <input type="text" size="50" name="calias" /><br /><br />
	<input type="submit" name="submit" value="'.$def_admin_addcat.'" />&nbsp;&nbsp;
	<input type="submit" name="submit" value="'.$def_admin_addsubcat.'" />&nbsp;&nbsp;
	<br /><br/>
	<input type="submit" name="submit" value="'.$def_admin_catren.'" />&nbsp;&nbsp;
	<input type="submit" name="submit" value="'.$def_admin_delcat.'" style="color: #FFFFFF; background: #D55454;" /></td></tr>';
        echo "\n";
	echo '</table></form><br /><br />';

	table_fdata_bottom();

}

 else {

if (isset ($_POST['id_cat'])) {

    
	$description=safeHTML($_POST['description']);
	$calias=safeHTML($_POST['calias']);
    $keywords=safeHTML($_POST['keywords']);
    $recomend=safeHTML($_POST['recomend']);
    $id_cat_post=intval($_POST['id_cat']);
    /*$text_description = str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $_POST['description_full']);
    $text_description = str_replace('iframe', '', $text_description);
    $text_description = str_replace('script', '', $text_description);
    $text_description = str_replace('alert', '', $text_description);*/
    $description_full=trim( $_POST['description_full']);
    $imgExt = array('gif', 'png', 'bmp', 'jpg', 'jpeg', 'tif', 'tiff');
    $images_r='';

    if ( isset($_FILES[key]) && is_uploaded_file($_FILES[key]['tmp_name']) )
		{
			$name	= strtolower($_FILES[key]['name']);
			$ext	= pathinfo($name, PATHINFO_EXTENSION);
			if (!in_array($ext, $imgExt))
			{
				msg_text('80%',$def_admin_message_error,'Загружайте разрешённые картинки.');
			}

                        else {

			$name	= '../images/category/'.$id_cat_post.'.' . $ext;

                        @unlink($name);

			if ( move_uploaded_file($_FILES[key]['tmp_name'], $name) )
			{
				$images_r = $ext;
			}
			else
                            {
                                	msg_text('80%',$def_admin_message_error,'Ошибка загрузки файла.');
                            }
                        }
		}

    if ($images_r!='') $db->query  ( " UPDATE $db_category SET description = '$description', keywords='$keywords', description_full='$description_full', recomend='$recomend', img='$images_r', calias='$calias' where selector='$id_cat_post' " ) or die ( mysql_error() );
    else $db->query  ( " UPDATE $db_category SET description = '$description', keywords='$keywords', description_full='$description_full', recomend='$recomend', calias='$calias' where selector='$id_cat_post' " ) or die ( mysql_error() );

    logsto("Выполнено редактирование категории <b>id=$id_cat_post</b>");

}

if (isset ($_POST['id_subcat'])) {
	$calias=safeHTML($_POST['calias']);
    $description=safeHTML($_POST['description']);
    $keywords=safeHTML($_POST['keywords']);
    $recomend=safeHTML($_POST['recomend']);
    $id_cat_post=intval($_POST['id_subcat']);
    
    $description_full=trim( $_POST['description_full']);
    
	$db->query  ( " UPDATE $db_subcategory SET description = '$description', keywords='$keywords', description_full='$description_full', calias='$calias' where catsubsel='$id_cat_post' " ) or die ( mysql_error() );

    logsto("Выполнено редактирование подкатегории <b>id=$id_cat_post</b>");

}

if ($_POST['do_delete'] == "Удалить иконку") {

    $id_cat_post=intval($_POST['id_cat']);
    $name="../images/category/$id_cat_post.$_POST[type_img]";
    @unlink($name);
    $db->query  ( " UPDATE $db_category SET img='' where selector='$id_cat_post' " ) or die ( mysql_error() );
    logsto("Удалена иконка к категории <b>id=$id_cat_post</b>");

}

    $help_section = (string)$cat2_help;

if (!empty($_GET['edcat'])) {
    $id_category=$_GET['edcat'];
	 $r_cat=$db->query ("select * from $db_category where selector='$id_category' LIMIT 1") or die ("mySQL error!");
} 
if (!empty($_GET['edsubcat'])){
    $id_category=$_GET['edsubcat'];
	 $r_cat=$db->query ("select * from $db_subcategory where catsubsel='$id_category' LIMIT 1") or die ("mySQL error!");
	 }

    $results_amount=mysql_numrows($r_cat);
    $f_cat=$db->fetcharray ($r_cat);

    $title_cp = 'Редактировать категорию - ';
    $speedbar = ' | <a href="edcat.php">'.$def_admin_edcat.'</a> | <a href="edcat.php?edcat='.$id_category.'">Редактировать категорию - '.$f_cat['category'].'</a>';

    require_once 'template/header.php';

    table_item_top ('Редактировать категорию - '.$f_cat['category'],'tmpl.png');

    table_fdata_top ($def_item_form_data);

    if ($results_amount==0) msg_text('80%',$def_admin_message_error,'Категория с данным id не найдена.');

    else {

?>

<script src="../includes/nicEdit.js" type="text/javascript"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
	new nicEditor().panelInstance('area_full');
});
</script>

 <form action="" method="post" enctype="multipart/form-data">
 <table width="900" border="0" cellspacing="2" cellpadding="2">
  <tr>
    <td align="right">Название категории:</td>
    <td align="left"><b><? echo $f_cat['category']; echo $f_cat['subcategory'];?></b></td>
  </tr>
  <tr>
    <td align="right">Адрес категории:</td>
    <td align="left"><input type="text" name="calias" value="<? echo $f_cat['calias']; ?>" style="width: 350px;" /></td>
  </tr>
  <tr>
    <td align="right">Описание категории (мета-тег Description):</td>
    <td align="left"><input type="text" name="description" value="<? echo $f_cat['description']; ?>" style="width: 350px;" /></td>
  </tr>
  <tr>
    <td align="right">Ключевые слова (мета-тег Keywords):</td>
    <td align="left"><textarea name="keywords" cols="45" rows="5"><? echo $f_cat['keywords']; ?></textarea></td>
  </tr>
  <tr>
    <td align="right">Описание категории:</td>
    <td align="left"><textarea name="description_full" cols="45" rows="5" id="area_full" style="width: 500px; height: 300px;"><? echo $f_cat['description_full']; ?></textarea></td>
  </tr>

  
  <tr>
    <td align="right">&nbsp;</td>
    <td align="left"><input type="submit" name="save" value="Сохранить" />
<?if (!empty($_GET['edcat'])) echo'
    <input type="hidden" name="id_cat" value="'.$f_cat['selector'].'" />'; else echo'
	<input type="hidden" name="id_subcat" value="'.$f_cat['catsubsel'].'" />';?>

    </td>
  </tr>
</table>
</form>
  
<?

    }

    table_fdata_bottom();

    

}

require_once 'template/footer.php';

?>